
package com.hlkj.pay.controller.common;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.hlkj.framework.caches.service.RedisTemplateService;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.common.ICommonAppService;
import com.hlkj.pay.common.constants.AdminRedisConstant;
import com.hlkj.pay.dto.Base64Dto;
import com.hlkj.pay.dto.LocalAdminUserRequest;
import com.hlkj.pay.dto.common.BankBranch;
import com.hlkj.pay.dto.common.BankBranchQuery;
import com.hlkj.pay.dto.common.ocr.OcrScan;
import com.hlkj.pay.dto.common.ocr.OcrScanResult;
import com.hlkj.pay.infrastructure.model.common.PlatFormConfigDO;
import com.hlkj.pay.service.common.IPlatFormConfigService;
import com.hlkj.pay.util.HttpUtils;

import cn.hutool.json.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;

/**
 * Description: 模板基础接口
 *
 * @author monk@techsun.com
 * @date 2023/3/23
 */
@Tag(name = "基础功能")
@RestController
@RequestMapping("/v1/common")
@RequiredArgsConstructor
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private final ICommonAppService commonAppService;

    private final IPlatFormConfigService platFormConfigService;
    private final RedisTemplateService redisTemplateService;

    @Value("${server.port}")
    private String serverPort;

    @Operation(summary = "port")
    @GetMapping("/port")
    CommonResult<String> serverPort() {
        return CommonResult.success(serverPort);
    }

    @Operation(summary = "ocr 识别")
    @GetMapping("/ocr")
    CommonResult<OcrScanResult> ocrScan(@Validated OcrScan ocrScan) {
        return commonAppService.ocrScan(ocrScan);
    }

    @Operation(summary = "urlToBase64")
    @GetMapping("/urlToBase64")
    CommonResult<String> urlToBase64(String url) {
        return commonAppService.urlToBase64(url);
    }
    @Operation(summary = "base64ToUrl")
    @PostMapping("/base64ToUrl")
    CommonResult<String> base64ToUrl(@RequestBody Base64Dto base64Dto) {
        return commonAppService.base64ToUrl(base64Dto);
    }
    @Operation(summary = "qrCode")
    @GetMapping("/qrCode")
    CommonResult<String> base64ToUrl(@Parameter(name = "url", description = "url") String url) {
        return commonAppService.qrCode(url);
    }

    @Operation(summary = "excel 模板")
    @GetMapping("/excelTemplate")
    CommonResult<String> excelTemplate(@Parameter(name = "type", description = "模板类型 100 代付") Integer type) {
        PlatFormConfigDO platFormConfigDO = platFormConfigService.excelTemplate(type);
        if (platFormConfigDO != null) {
            return CommonResult.success(platFormConfigDO.getConfigValue());
        }
        return CommonResult.success();
    }

    @Operation(summary = "联行号查询")
    @GetMapping("/brandCode")
    CommonResult<PageResult<BankBranch>> brandCode(BankBranchQuery bankBranchQuery) {
        PlatFormConfigDO platFormConfigDO = platFormConfigService.bankBranchAppcode();
        if (bankBranchQuery.getPageNo()== null) {
            bankBranchQuery.setPageNo(1);
        }
        String host = "https://jumdfty.market.alicloudapi.com";
        String path = "/lianhang/query";
        String method = "POST";
        String appcode = platFormConfigDO.getConfigValue();
        Map<String, String> headers = new HashMap<String, String>();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        // 根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("bank", bankBranchQuery.getBankName());
        bodys.put("bankcard", bankBranchQuery.getBankCardNo());
        bodys.put("city", bankBranchQuery.getCity());
        bodys.put("key", bankBranchQuery.getKey());
        bodys.put("page", bankBranchQuery.getPageNo().toString());
        bodys.put("province", bankBranchQuery.getProvince());
        log.info("联行号查询 bodys:{}",JsonUtils.toJsonString(bodys));
        LocalAdminUserRequest localAdminUserRequest=(LocalAdminUserRequest) LocalContext.get();
        String key=AdminRedisConstant.BRAND_CODE_KEY+localAdminUserRequest.getSn();
        Boolean hasKey = redisTemplateService.hasKey(key);
        if(hasKey){
            return CommonResult.error(1, "操作过快,请10秒后再试");
        }
        redisTemplateService.set(key,localAdminUserRequest.getSn(),10);
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode!=200){
                return CommonResult.error(1, "查询失败,返回码为:"+statusLine.getStatusCode()+",请检查参数是否正确");
            }
            JSONObject jsonObject = JsonUtils.parseObj(EntityUtils.toString(response.getEntity()));
            if (!jsonObject.get("code").toString().equals("200")) {
                return CommonResult.error(1, jsonObject.get("msg").toString());
            }
            log.info("联行号查询 response:{}",JsonUtils.toJsonString(jsonObject));
            JSONObject dataObject = jsonObject.getJSONObject("data");
            Object totalcount = dataObject.get("totalcount");
            Object record = dataObject.get("record");
            PageResult<BankBranch> pageResult = new PageResult<>();
            pageResult.setPageNo(1L);
            pageResult.setPageSize(bankBranchQuery.getPageSize().longValue());
            pageResult.setTotal(Long.valueOf(totalcount.toString()));
            if (record != null) {
                pageResult.setList(JsonUtils.parseArray(record.toString(), BankBranch.class));
            }
            return CommonResult.success(pageResult);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.success();
    }

}
